package com.xiaoshuidi.cloud.module.rooms.framework.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author hans.zhang
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CodeUtil {
    private final RedisTemplate redisTemplate;

    public String nextCode(String prefix) {
        return nextCode(prefix, 6);
    }

    public String nextCode(String prefix, int randomLength) {
        String no = null;
        while (true) {
            String randomCode = RandomUtil.randomString(randomLength);
            no = StrUtil.format(prefix + "{}{}", DateUtil.format(new Date(), "yyMMdd"), randomCode).toUpperCase();
            if (redisTemplate.opsForValue().setIfAbsent("code:" + no, 0, 24, TimeUnit.HOURS)) {
                break;
            }
        }
        return no;
    }
}
